﻿//创建时间: 2010-10-11
//创建作者: 李晓忠
//功能说明: CMS系统 结点信息
//最后修改: 2010-10-13 李晓忠 添加删除结点和子结点功能  
//最后修改: 2010-10-14 李晓忠 添加结点树  
//最后修改: 2010-10-28 李晓忠 移动结点 MoveNodeToNewParentId   
//最后修改: 2010-12-8 李晓忠 获取实结点的虚结点 
using System;
using System.Collections.Generic;
using System.Text;


using TRPOP.CMS.Model;
using TRPOP.CMS.DALFactory;
using TRPOP.Common;
using TRPOP.CMS.Plugin;

namespace TRPOP.CMS.Business
{
    public class NodeManage
    {
        private INodeDAL Idal;
        IAdminUser mIAdminUser = IAdminUserAccess.GetInstance();
        public NodeManage()
        {
            Idal = DataAccess.CreateNodeDAL();
        }

        #region 结点数量限制的辅助方法
        /// <summary>
        /// 获取当前版本可获取的结点数目
        /// </summary>
        /// <param name="intSelect">要查询的结点数量</param>
        /// <returns></returns>
        public int GetLimitNums(int intSelect)
        {
            return TRPOP.CMS.Plugin.VersionLimit.GetLimitNums(intSelect, TRPOP.CMS.Plugin.VersionLimit.NodeLimit);
        }
        /// <summary>
        /// 是否结点数量溢出
        /// </summary>
        /// <returns></returns>
        public bool IsOverFlow()
        {
            if (TRPOP.CMS.Plugin.VersionLimit.NodeLimit == -1)
                return false;
            return GetNodeListTree(0, 1, "").Count >= TRPOP.CMS.Plugin.VersionLimit.NodeLimit;
        }
        /// <summary>
        /// 获取现在所拥有的结点数目
        /// </summary>
        /// <returns></returns>
        public int GetPresentNodeNum()
        {
            return GetNodeListTree(0, 1, "").Count;
        }
        /// <summary>
        /// 获取父节点一级的结点总数
        /// </summary>
        /// <param name="intParentNodeID"></param>
        /// <returns></returns>
        public int GetGrandParentNodeNum(int intParentNodeID)
        {
            if (intParentNodeID == 0)
                return 0;
            return GetNodeListByParentID(GetInfoById(intParentNodeID).ParentId).Count;
        }
        /// <summary>
        /// 根据当前版本限制可访问的List数量
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oList"></param>
        public void GetLimitList<T>(List<T> oList)
        {
            if (oList == null)
                return;
            if (oList.Count <= TRPOP.CMS.Plugin.VersionLimit.NodeLimit)//如果查询的数量小于限制数量
                return;
            if (TRPOP.CMS.Plugin.VersionLimit.NodeLimit == -1)//如果无限制
                return;
            if (TRPOP.CMS.Plugin.VersionLimit.NodeLimit > 0 && oList.Count > TRPOP.CMS.Plugin.VersionLimit.NodeLimit)//如果有限制并且查询出的结果大于限制数量
                oList.RemoveAt(TRPOP.CMS.Plugin.VersionLimit.NodeLimit - 1);
            if (TRPOP.CMS.Plugin.VersionLimit.NodeLimit == 0)
                oList.RemoveAt(0);
        }
        /// <summary>
        /// 根据当前版本限制可访问的List数量
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oList"></param>
        public void GetLimitList<T>(List<T> oList, int intHaveOtherNodeIDNum)
        {
            if (oList == null)
                return;
            if (TRPOP.CMS.Plugin.VersionLimit.NodeLimit == -1)//如果无限制
                return;
            if ((oList.Count + intHaveOtherNodeIDNum) <= TRPOP.CMS.Plugin.VersionLimit.NodeLimit)//如果查询的数量小于限制数量
                return;
            if (TRPOP.CMS.Plugin.VersionLimit.NodeLimit == 0)
                oList.RemoveAt(0);
            int intCanRead = TRPOP.CMS.Plugin.VersionLimit.NodeLimit - intHaveOtherNodeIDNum;
            if (intCanRead >= oList.Count || intCanRead <= 0)
                return;
            oList.RemoveAt(intCanRead - 1);
        }
        #endregion

        #region 用户权限认证
        /// <summary>
        /// 保存当前限制的结点
        /// </summary>
        public string GetNodeCondation()
        {
            string strNodeConadtion = mIAdminUser.GetEnabledNodeIds().ToLower().Trim();
            if (strNodeConadtion.IsEmpty() || strNodeConadtion == "all")
                return " ";

            return string.Format("  and NodeId in ({0})  ", strNodeConadtion);
        }
        #endregion

        #region 当编辑时删除所有已之相关的缓存
        /// <summary>
        /// 当编辑时删除所有已之相关的缓存
        /// </summary>
        /// <param name="oEnumSubmitResult"></param>
        /// <returns></returns>
        public EnumSubmitResult RemoveCacheWhenEdit(EnumSubmitResult oEnumSubmitResult)
        {
            if (oEnumSubmitResult == EnumSubmitResult.Success)
            {
                ICacheAccess.GetInstance().RemoveByRegexp(CacheKeys.CacheReg_NodeAll);
            }
            return oEnumSubmitResult;
        }
        #endregion

        #region 保存 Save
        ///	<summary>
        ///	保存
        ///	</summary>
        ///	<param name="NodeInfo"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult Save(NodeInfo info)
        {
            //return RemoveCacheWhenEdit(Idal.Save(info));
            //将用户信息重新加载
            EnumSubmitResult enumReturn = EnumSubmitResult.Failed;
            if (info.NodeId <= 0)
            {
                enumReturn = Idal.Save(info);
                if (enumReturn == EnumSubmitResult.Success)
                {
                    SetParentAndChild(info);
                    Idal.Save(info);
                    //修改所有父节点的结点关系
                    NodeInfo oTempInfo = GetInfoById(info.ParentId);
                    while (oTempInfo != null)
                    {
                        SetParentAndChild(oTempInfo);
                        Idal.Save(oTempInfo);
                        oTempInfo = GetInfoById(oTempInfo.ParentId);
                    }
                    //
                }
                mIAdminUser.AddPermissionByNodeId(info.NodeId);
                return RemoveCacheWhenEdit(enumReturn);
            }
            else
            {
                SetParentAndChild(info);
                enumReturn = RemoveCacheWhenEdit(Idal.Save(info));
                //修改附件表对应的fileURL
                SaveNodeURLForSourcePSN(info);
                return enumReturn;
            }
        }
        #endregion

        #region 获取实体 GetInfoById
        ///	<summary>
        ///	获取实体
        ///	</summary>
        ///	<param name="nodeId"></param>
        ///	<returns>NodeInfo</returns>
        public NodeInfo GetInfoById(int id)
        {
            //string strCacheKey = string.Format(CacheKeys.Node_GetInfoById, id);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    NodeInfo oNodeInfo = Idal.GetInfoById(id);
            //    mICache.Save(strCacheKey, oNodeInfo, CacheKeys.NodeTimeSecond);
            //    return oNodeInfo;
            //}
            //return (NodeInfo)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<NodeInfo>(
                    string.Format(CacheKeys.Node_GetInfoById, id),
                    CacheKeys.ModelTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        return Idal.GetInfoById(id);
                    }
                );
        }
        #endregion

        #region 删除 DeleteInfoById
        ///	<summary>
        ///	删除
        ///	</summary>
        ///	<param name="id"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult DeleteInfoById(int id)
        {
            return RemoveCacheWhenEdit(Idal.DeleteInfoByIds(id.ToString()));
        }
        #endregion

        #region 删除 DeleteInfoByIds
        ///	<summary>
        ///	删除
        ///	</summary>
        ///	<param name="ids"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult DeleteInfoByIds(string ids)
        {
            return RemoveCacheWhenEdit(Idal.DeleteInfoByIds(ids));
        }
        #endregion

        #region 逻辑删除结点和子结点 DeleteNodeAndChildrenById
        ///	<summary>
        ///	逻辑删除结点和子结点
        ///	</summary>
        ///	<param name="ids"></param>
        ///	<returns>EnumSubmitResult</returns>
        public EnumSubmitResult DeleteNodeAndChildrenById(int id)
        {
            return RemoveCacheWhenEdit(Idal.DeleteNodeAndChildrenById(id));
        }
        #endregion

        #region 自定义列表（无分页） GetListByCondition
        ///	<summary>
        ///	自定义列表（无分页）
        ///	</summary>
        ///	<param name="topn">前N条，为0时表示所有符合条件的</param>
        ///	<param name="condition">自定义条件，要以And开头</param>
        ///	<param name="orderby">排序，不需要Order by </param>
        ///	<returns>List<NodeInfo></returns>
        public List<NodeInfo> GetListByCondition(int topn, string condition, string orderby)
        {
            topn = GetLimitNums(topn);
            return Idal.GetListByCondition(topn, condition + GetNodeCondation(), orderby);
        }
        ///	<summary>
        ///	自定义列表（无分页）
        ///	</summary>
        ///	<param name="topn">前N条，为0时表示所有符合条件的</param>
        ///	<param name="condition">自定义条件，要以And开头</param>
        ///	<param name="orderby">排序，不需要Order by </param>
        ///	<returns>List<NodeInfo></returns>
        public List<NodeInfo> GetListByConditionNotLimit(int topn, string condition, string orderby)
        {
            return Idal.GetListByCondition(topn, condition, orderby);
        }
        ///	<summary>
        ///	自定义列表（无分页）
        ///	</summary>
        ///	<param name="topn">前N条，为0时表示所有符合条件的</param>
        ///	<param name="condition">自定义条件，要以And开头</param>
        ///	<param name="orderby">排序，不需要Order by </param>
        ///	<returns>List<NodeInfo></returns>
        public List<NodeInfo> GetListByConditionWithoutUnLinked(int topn, string condition, string orderby)
        {
            topn = GetLimitNums(topn);
            string strNodeConadtion = mIAdminUser.GetEnabledNodeIds().ToLower().Trim();
            if (strNodeConadtion.IsEmpty() || strNodeConadtion == "all")
                return Idal.GetListByCondition(topn, condition, orderby);
            StringBuilder strbuild = new StringBuilder();
            foreach (string strTemp in strNodeConadtion.Split(','))
            {
                if (!strTemp.IsEmpty())
                {
                    strbuild.Append(" or  [ArrChildId] like '%," + strTemp + ",%'    ");
                }
            }
            strbuild.Insert(0, " 1 <> 1 ");
            condition += string.Format("  and ( {0} )  ", strbuild.ToString());
            return Idal.GetListByCondition(topn, condition, orderby);
            //之前的实现方式
            //return Idal.GetListByCondition(topn, condition, orderby);
        }
        #endregion

        #region 自定义列表（分页） GetListByPager
        ///	<summary>
        ///	自定义列表（分页）
        ///	</summary>
        ///	<returns>List<NodeInfo></returns>
        public List<NodeInfo> GetListByPager(int pageNumber, int pageSize, string condition, string orderby, out int recordCount)
        {
            return Idal.GetListByPager(pageNumber, pageSize, condition + GetNodeCondation(), orderby, out  recordCount);
        }
        #endregion

        #region 结点 树形结构 GetNodeListTree
        /// <summary>
        /// 结点树形结构
        /// </summary>
        /// <param name="ParentId"></param>
        /// <param name="level"></param>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public List<NodeInfoWithLevel> GetNodeListTree(int ParentId, int level, string Condition, bool IsAll)
        {
            //if (IsAll == false)
            //    Condition = GetNodeCondation() + Condition;
            //string strCacheKey = string.Format(CacheKeys.Node_GetNodeListTree, ParentId, level, Condition);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    List<NodeInfoWithLevel> olist = Idal.GetNodeListTree(ParentId, level, " and IsHidde=0  " + Condition);
            //    GetLimitList<NodeInfoWithLevel>(olist);//数量限制
            //    mICache.Save(strCacheKey, olist, CacheKeys.NodeTimeSecond);
            //    return olist;
            //}
            //return (List<NodeInfoWithLevel>)mICache.Read(strCacheKey);
            if (IsAll == false)
                Condition = GetNodeCondation() + Condition;
            return CacheHelper.GetByICache<List<NodeInfoWithLevel>>(
                    string.Format(CacheKeys.Node_GetNodeListTree, ParentId, level, Condition),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        List<NodeInfoWithLevel> olist = Idal.GetNodeListTree(ParentId, level, " and IsHidde=0  " + Condition);
                        GetLimitList<NodeInfoWithLevel>(olist);//数量限制
                        return olist;
                    }
                );
        }

        /// <summary>
        /// 结点树形结构
        /// </summary>
        /// <param name="ParentId"></param>
        /// <param name="level"></param>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public List<NodeInfoWithLevel> GetNodeListTree(int ParentId, int level, string Condition)
        {
            //Condition = Condition + GetNodeCondation();
            //string strCacheKey = string.Format(CacheKeys.Node_GetNodeListTree, ParentId, level, Condition);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    List<NodeInfoWithLevel> olist = Idal.GetNodeListTree(ParentId, level, Condition + " and IsHidde=0  ");
            //    GetLimitList<NodeInfoWithLevel>(olist);//数量限制
            //    mICache.Save(strCacheKey, olist, CacheKeys.NodeTimeSecond);
            //    return olist;
            //}
            //return (List<NodeInfoWithLevel>)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<List<NodeInfoWithLevel>>(
                    string.Format(CacheKeys.Node_GetNodeListTree, ParentId, level, Condition + GetNodeCondation()),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        List<NodeInfoWithLevel> olist = Idal.GetNodeListTree(ParentId, level, Condition + " and IsHidde=0  ");
                        GetLimitList<NodeInfoWithLevel>(olist);//数量限制
                        return olist;
                    }
                );
        }
        #endregion

        #region 移动结点 MoveNodeToNewParentId
        /// <summary>
        /// 移动结点
        /// </summary>
        /// <param name="nodeid"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public EnumSubmitResult MoveNodeToNewParentId(int nodeid, int parentId)
        {
            NodeInfo oNodeInfo = GetInfoById(nodeid);
            if (oNodeInfo != null)
            {
                // 重新修改之前的父节点的结点关系
                NodeInfo oTempInfo = GetInfoById(oNodeInfo.ParentId);
                while (oTempInfo != null)
                {
                    Save(oTempInfo);
                    oTempInfo = GetInfoById(oTempInfo.ParentId);
                }
                //
                oNodeInfo.ParentId = parentId;
                if (Save(oNodeInfo) == EnumSubmitResult.Success)
                {
                    oTempInfo = GetInfoById(parentId);
                    while (oTempInfo != null)
                    {
                        Save(oTempInfo);
                        oTempInfo = GetInfoById(oTempInfo.ParentId);
                    }
                    return EnumSubmitResult.Success;
                }
            }
            return EnumSubmitResult.Failed;
            //之前的代码
            //return RemoveCacheWhenEdit(Idal.MoveNodeToNewParentId(nodeid, parentId));
        }
        #endregion

        #region 永久删除结点和结点相关的信息 DestroyNodeAndContetnById
        /// <summary>
        /// 删除结点下所有内容
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isDelFile">是否删除发布页</param>
        /// <param name="isDelAttr">删除上传附件</param>
        /// <param name="isDelImg">删除上传图片</param>
        /// <returns></returns>
        public EnumSubmitResult DestroyNodeAndContetnById(int id, bool isDelFile, bool isDelAttr, bool isDelImg)
        {
            return RemoveCacheWhenEdit(DeleteNodeById(id, isDelFile, isDelAttr, isDelImg));
        }
        #endregion

        #region 获取结点名 GetNodeNameById
        /// <summary>
        ///  获取结点名 GetNodeNameById
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetNodeNameById(int id)
        {
            //string strCacheKey = string.Format(CacheKeys.Node_GetNodeNameById, id);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    //
            //    NodeInfo m_NodeInfo = new NodeInfo();
            //    m_NodeInfo = GetInfoById(id);
            //    if (m_NodeInfo == null)
            //    {
            //        m_NodeInfo = new NodeInfo();
            //    }
            //    mICache.Save(strCacheKey, m_NodeInfo.Name, CacheKeys.NodeTimeSecond);
            //    return m_NodeInfo.Name;
            //}
            //return (string)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<string>(
                    string.Format(CacheKeys.Node_GetNodeNameById, id),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        NodeInfo m_NodeInfo = new NodeInfo();
                        m_NodeInfo = GetInfoById(id);
                        if (m_NodeInfo == null)
                        {
                            m_NodeInfo = new NodeInfo();
                        }
                        return m_NodeInfo.Name;
                    }
                );
        }
        #endregion

        #region 返回目录规则
        /// <summary>
        ///  返回目录规则
        /// </summary>
        /// <param name="reg"></param>
        /// <param name="dateTime">addtime</param>
        /// <returns></returns>
        public string RootReg(string reg, DateTime dateTime)
        {
            return TRPOP.Common.CommonRegex.GetConvertRoot(reg, dateTime);
        }
        #endregion

        #region 返回生成的文件名

        /// <summary>
        /// 根据生成规则  返回生成的文件名
        /// </summary>
        /// <param name="NameReg">命名规则</param>
        /// <param name="ExtentId">基表信息Id替换{ContentID}</param>
        /// <param name="NodeId">结点Id</param>
        /// <param name="ContentId">基表信息Id替换{IndexID}</param>
        /// <param name="Page">分页Id替换{Page}</param>
        /// <param name="AddTime">添加时间</param>
        /// <returns></returns>
        public string PageName(string NameReg, int ExtentId, int NodeId, int ContentId, int Page, DateTime AddTime)
        {
            StringBuilder strHtmlName = new StringBuilder();
            strHtmlName.Append(NameReg.ToLower());
            strHtmlName = strHtmlName.Replace("{timestamp}", AddTime.ToString("yyyyMMddHHmmss"));
            strHtmlName = strHtmlName.Replace("{nodeid}", NodeId.ToString());
            strHtmlName = strHtmlName.Replace("{contentid}", ContentId.ToString());
            strHtmlName = strHtmlName.Replace("{indexid}", ContentId.ToString());
            strHtmlName = strHtmlName.Replace("{page}", Page.ToString());
            return strHtmlName.ToString();
        }
        #endregion

        #region 获取结点首页地址
        /// <summary>
        /// 获取结点首页地址
        /// </summary>
        /// <param name="NodeId"></param>
        /// <returns></returns>
        public string GetNodeIndexPage(int NodeId)
        {
            //string strCacheKey = string.Format(CacheKeys.Node_GetNodeIndexPage, NodeId);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    string strURL = "";
            //    if (NodeId > 0)
            //    {
            //        NodeInfo m_NodeInfo = GetInfoById(NodeId);
            //        strURL = m_NodeInfo.Url;
            //    }
            //    mICache.Save(strCacheKey, strURL, CacheKeys.NodeTimeSecond);
            //    return strURL;
            //}
            //return (string)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<string>(
                    string.Format(CacheKeys.Node_GetNodeIndexPage, NodeId),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        string strURL = "";
                        if (NodeId > 0)
                        {
                            NodeInfo m_NodeInfo = GetInfoById(NodeId);
                            strURL = m_NodeInfo.Url;
                        }
                        return strURL;
                    }
                );
        }
        #endregion

        #region 获取实结点的虚结点
        /// <summary>
        /// 获取实结点的虚结点
        /// </summary>
        /// <param name="TrueNodeID">实结点Id</param>
        /// <returns></returns>
        public List<NodeInfo> GetVirualNode(int TrueNodeID)
        {
            //string strCacheKey = string.Format(CacheKeys.Node_GetVirualNode, TrueNodeID);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    List<NodeInfo> m_NodeList = new List<NodeInfo>();
            //    string strCondition = " AND IsHidde=0 "
            //                                        + "AND InheritNodeID=" + TrueNodeID
            //                                       + "AND NodeTypeId=" + (int)NodeType.EnumElement.VirualNode;
            //    m_NodeList = GetListByCondition(0, strCondition, " NodeId desc");
            //    mICache.Save(strCacheKey, m_NodeList, CacheKeys.NodeTimeSecond);
            //    return m_NodeList;
            //}
            //return (List<NodeInfo>)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<List<NodeInfo>>(
                    string.Format(CacheKeys.Node_GetVirualNode, TrueNodeID),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        List<NodeInfo> m_NodeList = new List<NodeInfo>();
                        string strCondition = " AND IsHidde=0 "
                                                            + "AND InheritNodeID=" + TrueNodeID
                                                           + "AND NodeTypeId=" + (int)NodeType.EnumElement.VirualNode;
                        return GetListByConditionNotLimit(0, strCondition, " NodeId desc");
                    }
                );
        }
        #endregion

        #region 获取静态发布结点首页发布地址
        /// <summary>
        /// 获取静态发布结点首页发布地址,不含页面名
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public string GetIndexPSNPath(NodeInfo info)
        {
            //if (info == null)
            //    return "";
            //string strCacheKey = string.Format(CacheKeys.Node_GetIndexPSNPath, info.NodeId);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    string strPath = "";
            //    if (info.ContentPubTypeId == (int)ContentPubType.EnumElement.StaticPub)
            //    {
            //        PSNManage m_PSNManage = new PSNManage();
            //        PSNInfo m_PSNInfo = new PSNInfo();
            //        if (info.HtmlPSN != "")
            //        {
            //            strPath = m_PSNManage.GetPSNPathByPSN(info.HtmlPSN);

            //        }
            //        else if (SYSConfig.DefaultContentPSN != "")
            //        {
            //            strPath = m_PSNManage.GetPSNPathByPSN(SYSConfig.DefaultContentPSN);
            //        }
            //        strPath = strPath.Replace("//", "/");
            //    }
            //    mICache.Save(strCacheKey, strPath, CacheKeys.NodeTimeSecond);
            //    return strPath;
            //}
            //return (string)mICache.Read(strCacheKey);
            if (info == null)
                return "";
            return CacheHelper.GetByICache<string>(
                    string.Format(CacheKeys.Node_GetIndexPSNPath, info.NodeId),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        string strPath = "";
                        if (info.ContentPubTypeId == (int)ContentPubType.EnumElement.StaticPub)
                        {
                            PSNManage m_PSNManage = new PSNManage();
                            PSNInfo m_PSNInfo = new PSNInfo();
                            if (info.HtmlPSN != "")
                            {
                                strPath = m_PSNManage.GetPSNPathByPSN(info.HtmlPSN);

                            }
                            else if (SYSConfig.SystemVar_DefaultContentPSN != "")
                            {
                                strPath = m_PSNManage.GetPSNPathByPSN(SYSConfig.SystemVar_DefaultContentPSN);
                            }
                            strPath = strPath.Replace("//", "/");
                        }
                        return strPath;
                    }
                );
        }
        /// <summary>
        /// 获取静态发布结点首页发布地址,不含页面名
        /// </summary>
        /// <param name="NodeId"></param>
        /// <returns></returns>
        public string GetIndexPSNPath(int NodeId)
        {
            //string strCacheKey = string.Format(CacheKeys.Node_GetIndexPSNPath, NodeId);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    string strPath = "";
            //    NodeInfo info = GetInfoById(NodeId);
            //    if (info != null)
            //    {
            //        if (info.ContentPubTypeId == (int)ContentPubType.EnumElement.StaticPub)
            //        {
            //            PSNManage m_PSNManage = new PSNManage();
            //            PSNInfo m_PSNInfo = new PSNInfo();

            //            if (info.HtmlPSN != "")
            //            {
            //                strPath = m_PSNManage.GetPSNPathByPSN(info.HtmlPSN);

            //            }
            //            else if (SYSConfig.DefaultContentPSN != "")
            //            {
            //                strPath = m_PSNManage.GetPSNPathByPSN(SYSConfig.DefaultContentPSN);
            //            }
            //            strPath = strPath.Replace("//", "/");
            //        }
            //    }
            //    mICache.Save(strCacheKey, strPath, CacheKeys.NodeTimeSecond);
            //    return strPath;
            //}
            //return (string)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<string>(
                    string.Format(CacheKeys.Node_GetIndexPSNPath, NodeId),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        string strPath = "";
                        NodeInfo info = GetInfoById(NodeId);
                        if (info != null)
                        {
                            if (info.ContentPubTypeId == (int)ContentPubType.EnumElement.StaticPub)
                            {
                                PSNManage m_PSNManage = new PSNManage();
                                PSNInfo m_PSNInfo = new PSNInfo();

                                if (info.HtmlPSN != "")
                                {
                                    strPath = m_PSNManage.GetPSNPathByPSN(info.HtmlPSN);

                                }
                                else if (SYSConfig.SystemVar_DefaultContentPSN != "")
                                {
                                    strPath = m_PSNManage.GetPSNPathByPSN(SYSConfig.SystemVar_DefaultContentPSN);
                                }
                                strPath = strPath.Replace("//", "/");
                            }
                        }
                        return strPath;
                    }
                );
        }
        #endregion

        #region 获取结点下所有子结点(保含子结点的子结点)
        /// <summary>
        /// 获取结点下所有子结点(保含子结点的子结点)
        /// </summary>
        /// <param name="ParentID">结点ID</param>
        /// <returns></returns>
        public List<NodeInfo> GetNodeListByParentID(int ParentID)
        {
            //string strCacheKey = string.Format(CacheKeys.Node_GetNodeListByParentID, ParentID);
            //if (mICache.IsExist(strCacheKey) == false)
            //{
            //    List<NodeInfo> olist = Idal.GetNodeListByParentID(ParentID);
            //    GetLimitList<NodeInfo>(olist, GetGrandParentNodeNum(ParentID));//数量限制
            //    mICache.Save(strCacheKey, olist, CacheKeys.NodeTimeSecond);
            //    return olist;
            //}
            //return (List<NodeInfo>)mICache.Read(strCacheKey);
            return CacheHelper.GetByICache<List<NodeInfo>>(
                    string.Format(CacheKeys.Node_GetNodeListByParentID, ParentID),
                    CacheKeys.NodeTimeSecond,
                    ICacheAccess.GetInstance(),
                    () =>
                    {
                        List<NodeInfo> olist = Idal.GetNodeListByParentID(ParentID);
                        GetLimitList<NodeInfo>(olist, GetGrandParentNodeNum(ParentID));//数量限制
                        return olist;
                    }
                );
        }
        #endregion

        #region 永久删除结点
        /// <summary>
        /// 永久删除结点
        /// </summary>
        /// <param name="Id"></param>
        ///  <param name="isDelFile">删除发布的静态页</param>
        /// <param name="isDelAttr">删除上传附件</param>
        /// <param name="isDelImg">删除上传图片</param>
        /// <returns></returns>
        public EnumSubmitResult DeleteNodeById(int Id, bool isDelFile, bool isDelAttr, bool isDelImg)
        {
            EnumSubmitResult esrResult = EnumSubmitResult.Success;
            ContentManage m_ContentManage = new ContentManage();
            #region 处理结点下页的信息
            NodeInfo info = GetInfoById(Id);
            if (info != null)
            {
                //删除结点首页
                if (isDelFile)
                {
                    string IndexPath = GetIndexPSNPath(info);
                    IndexPath = IndexPath + "/" + info.IndexName;
                    IndexPath = IndexPath.Replace("//", "/");
                    FileUtil.DeleteFile(IndexPath, false, "");
                }
                //删除结点下信息
                esrResult = m_ContentManage.DeleteInfoByNodeId(Id, isDelFile, isDelAttr, isDelImg);
            }
            #endregion
            //删除结点
            esrResult = DeleteInfoById(Id);
            return RemoveCacheWhenEdit(esrResult);
        }
        #endregion

        #region 找到所有的父节点，并且针对父节点进行 [ParentPath] 和 [ArrChildId] 的修改
        /// <summary>
        /// 修改当前结点信息的 arrchild 和parentPath，单不保存信息
        /// </summary>
        /// <param name="oBottomInfo"></param>
        public void SetParentAndChild(NodeInfo oBottomInfo)
        {
            if (oBottomInfo == null)
                return;
            //针对ArrChildID的修改
            StringBuilder strBuild = new StringBuilder("," + oBottomInfo.NodeId + ",");
            List<NodeInfo> oChildList = GetNodeListByParentID(oBottomInfo.NodeId);
            foreach (NodeInfo oTemoInfo in oChildList)
            {
                if (oTemoInfo.NodeId == oBottomInfo.NodeId)
                    continue;
                strBuild.Append(oTemoInfo.NodeId + ",");
            }
            oBottomInfo.ArrChildId = strBuild.ToString();
            //针对[ParentPath] 进行修改
            strBuild.Remove(0, strBuild.Length);
            NodeInfo oTempInfo = GetInfoById(oBottomInfo.ParentId);
            while (oTempInfo != null)
            {
                strBuild.Insert(0, "," + oTempInfo.NodeId);
                oTempInfo = GetInfoById(oTempInfo.ParentId);
            }
            strBuild.Insert(0, "0");
            if (oBottomInfo.ParentPath.Trim() == strBuild.ToString().Trim())
            {
                ResetUnlinkedParentInfo(oBottomInfo);
            }
            oBottomInfo.ParentPath = strBuild.ToString();
        }
        /// <summary>
        /// 重新保存父节点的 arrchild 和 parentPath
        /// </summary>
        /// <param name="oNodeInfo"></param>
        public void ResetUnlinkedParentInfo(NodeInfo oNodeInfo)
        {
            foreach (string strTempId in oNodeInfo.ParentPath.Split(','))
            {
                if (!strTempId.IsEmpty())
                {
                    NodeInfo oTempNodeInfo = GetInfoById(strTempId.ToInt());
                    if (oTempNodeInfo != null)
                    {
                        SetParentAndChild(oTempNodeInfo);
                        Save(oTempNodeInfo);
                    }
                }
            }
        }
        #endregion

        #region 附件 和 结点 的处理
        /// <summary>
        /// 更新附件列表里的数据
        /// </summary>
        /// <param name="oNodeInfo"></param>
        /// <param name="strOld"></param>
        public void ResetAllPSN(NodeInfo oNodeInfo, string strOld)
        {
            PSNManage oPSNManage = new PSNManage();
            string stroldRoot = oPSNManage.GetPSNPathByPSN(strOld);
            if (strOld == stroldRoot)
                return;
            string strNewRoot = oPSNManage.GetPSNPathByPSN(oNodeInfo.SourcePSN);
            if (strNewRoot == stroldRoot)
                return;
            Idal.ResetAllPSN(oNodeInfo.NodeId.ToString(), stroldRoot, strNewRoot);
        }

        /// <summary>
        /// 获取结点的PSNRoot URL对应关系:
        /// 1 结点id_PSNSourceRoot 结点id_PSNSourceRootURL
        /// </summary>
        /// <returns></returns>
        public SerializableDictionary<string, string> GetNodeURLForSourcePSN()
        {
            SerializableDictionary<string, string> oDictionary;
            string strDictionary = string.Empty;
            if (FileUtil.IsExist(Common.Util.GetMapPath(CommonKeys.pathNodeURLForSourcePSN)))
            {
                strDictionary = FileUtil.ReadFile(Common.Util.GetMapPath(CommonKeys.pathNodeURLForSourcePSN));
            }
            if (strDictionary.IsEmpty())
                return new SerializableDictionary<string, string>();
            else
            {
                oDictionary = SerializationHelper.GetObj(strDictionary, typeof(SerializableDictionary<string, string>)) as SerializableDictionary<string, string>;
                if (oDictionary == null)
                    return new SerializableDictionary<string, string>();
                else
                    return oDictionary;
            }
        }
        /// <summary>
        /// 保存缓存文件: 结点sourceURL关系
        /// </summary>
        /// <param name="oNodeInfo"></param>
        /// <returns></returns>
        public SerializableDictionary<string, string> SaveNodeURLForSourcePSN(NodeInfo oNodeInfo)
        {
            SerializableDictionary<string, string> oDictionary = GetNodeURLForSourcePSN();
            if (oNodeInfo == null || oNodeInfo.NodeId == 0)
                return oDictionary;
            PSNManage oPSNManage = new PSNManage();
            string strPSNSourceRoot = oNodeInfo.NodeId + "_PSNSourceRoot";
            string strPSNSourceRootURL = oNodeInfo.NodeId + "_PSNSourceRootURL";
            string strPSNSourceRoot_value = oPSNManage.GetPSNPathByPSN(oNodeInfo.SourcePSN);
            string strPSNSourceRootURL_value = oPSNManage.GetPSNURLByPSNUrl(oNodeInfo.SourceUrl);
            if (oDictionary.ContainsKey(strPSNSourceRoot))
                oDictionary.Remove(strPSNSourceRoot);
            if (oDictionary.ContainsKey(strPSNSourceRootURL))
                oDictionary.Remove(strPSNSourceRootURL);
            oDictionary.Add(strPSNSourceRoot, strPSNSourceRoot_value);
            oDictionary.Add(strPSNSourceRootURL, strPSNSourceRootURL_value);
            FileUtil.WriteFile(Common.Util.GetMapPath(CommonKeys.pathNodeURLForSourcePSN), SerializationHelper.GetString(typeof(SerializableDictionary<string, string>), oDictionary));
            return oDictionary;
        }
        /// <summary>
        /// 保存缓存文件: 结点sourceURL关系
        /// </summary>
        /// <param name="oNodeInfo"></param>
        /// <returns></returns>
        public SerializableDictionary<string, string> SaveNullNodeURLForSourcePSN()
        {
            SerializableDictionary<string, string> oDictionary = GetNodeURLForSourcePSN();
            PSNManage oPSNManage = new PSNManage();
            string strPSNSourceRoot = "0_PSNSourceRoot";
            string strPSNSourceRootURL = "0_PSNSourceRootURL";
            string strPSNSourceRoot_value = oPSNManage.GetPSNPathByPSN(SYSConfig.SystemVar_DefaultResourcePSN);
            string strPSNSourceRootURL_value = oPSNManage.GetPSNURLByPSNUrl(SYSConfig.SystemVar_DefaultResourcePSNURL);
            if (oDictionary.ContainsKey(strPSNSourceRoot))
                oDictionary.Remove(strPSNSourceRoot);
            if (oDictionary.ContainsKey(strPSNSourceRootURL))
                oDictionary.Remove(strPSNSourceRootURL);
            oDictionary.Add(strPSNSourceRoot, strPSNSourceRoot_value);
            oDictionary.Add(strPSNSourceRootURL, strPSNSourceRootURL_value);
            FileUtil.WriteFile(Common.Util.GetMapPath(CommonKeys.pathNodeURLForSourcePSN), SerializationHelper.GetString(typeof(SerializableDictionary<string, string>), oDictionary));
            return oDictionary;
        }
        #endregion
    }
}
